package com.iknowone.servlet;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iknowone.db.DbManager;
import com.iknowone.entity.Params;
import com.iknowone.entity.Rating;
import com.iknowone.entity.Result;
import com.iknowone.entity.Status;

public class AddRatingServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected Result getResult(HttpServletRequest req) {
		DbManager dbManager = new DbManager();
		String strStars = req.getParameter(Params.STARS.getValue());
		String comment = req.getParameter(Params.COMMENT.getValue());
		String userId = req.getParameter(Params.USER_ID.getValue());
		String poiId = req.getParameter(Params.POI_ID.getValue());

		Status status = checkMandatoryParameter(Params.USER_ID, req);
		if (status.getHttpCode() == HttpServletResponse.SC_OK) {
			status = checkMandatoryParameter(Params.POI_ID, req);
		}
		if (status.getHttpCode() == HttpServletResponse.SC_OK) {
			status = checkMandatoryParameter(Params.STARS, req);
		}
		if (status.getHttpCode() == HttpServletResponse.SC_OK) {
			status = checkMandatoryParameter(Params.COMMENT, req);
		}
		if (status.getHttpCode() == HttpServletResponse.SC_OK) {
			try {
				Integer stars = Integer.valueOf(strStars);
				dbManager.save(new Rating(poiId, userId, stars, comment,
						new Date()));
			} catch (NumberFormatException e) {
				status = new Status(HttpServletResponse.SC_BAD_REQUEST,
						"Invalid number - stars.");
			} catch (Exception e) {
				status = new Status(
						HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
						"Internal error.");
			}
		}
		return new Result(null, status);
	}
}